'''
@Description: In User Settings Edit
@Author: your name
@Date: 2019-07-15 11:38:44
@LastEditTime: 2020-02-19 16:19:08
@LastEditors: Please set LastEditors
'''

from ...pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, data_to_string_date
from ...service.common import insert_data, find_data, update_data, delete_data, get_condition, get_info, get_serial_number, SerialNumberType
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status
from ...service.mongo_bill_service import MongoBillFilter
from ...pao_python.pao.data import DataList


class BusinessAreaService(MongoService):
    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        DataProcess.__init__(self, db_addr, db_port, db_name, db_user, db_pwd)
        # self.db_name = db_name
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_server = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

    def get_business_area_list(self, org_list, condition, page=None, count=None):
        '''# 查询业务区域列表'''
        keys = ['id', 'org_name']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.lookup_bill('PT_User', 'organization_id', 'id', 'org')\
            .add_fields({'org_name': '$org.name'})\
            .match_bill((C('id') == values['id']) & (C('org_name').like(values['org_name'])) & (C('organization_id').inner(org_list)))\
            .project({'_id': 0, 'org._id': 0})
        res = self.page_query(_filter, "PT_Business_Area", page, count)
        return res

    def add_business_area(self, businessArea):
        '''# 新增业务区域'''
        res = 'Fail'
        data_info = get_info({**businessArea}, self.session)

        def process_func(db):
            nonlocal res
            if 'id' in businessArea.keys():
                flag = OperationType.update.value
            else:
                flag = OperationType.add.value
            bill_id = self.bill_manage_server.add_bill(flag,
                                                       TypeId.businessArea.value, data_info, 'PT_Business_Area')
            if bill_id:
                res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def del_business_area(self, ids):
        '''# 删除业务区域'''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            for business_id in ids:
                data = find_data(db, 'PT_Business_Area', {
                    'id': business_id, 'bill_status': Status.bill_valid.value})
                if len(data) > 0:
                    self.bill_manage_server.add_bill(OperationType.delete.value,
                                                     TypeId.businessArea.value, data[0], 'PT_Business_Area')
            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def update_business_area_dispose(self, businessAreaDispose):
        '''# 修改业务区域配置'''
        res = 'Fail'

        def process_func(db):
            nonlocal res

            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def copy_business_area_dispose(self, business_area_id):
        '''# 复制业务区域数据'''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            data = find_data(db, 'PT_Business_Area', {
                'id': business_area_id, 'status':  Status.bill_valid.value})
            data.pop('_id')
            data.pop('id')
            data.pop('create_date')
            new_data = get_info(data, self.session)
            self.bill_manage_server.add_bill(OperationType.add.value,
                                             TypeId.businessArea.value, new_data, 'PT_Business_Area')

            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def get_business_area_item(self, condition, page=None, count=None):
        '''# 查询业务区域配置项列表'''
        _filter = MongoFilter()
        _filter.add_fields({
            'create_date': self.ao.date_to_string('$create_date'),
            'modify_date': self.ao.date_to_string('$modify_date')})\
            .match((C('bill_status') == Status.bill_valid.value))\
            .project({'_id': 0})
        res = self.page_query(_filter, "PT_Business_Area_Item", page, count)
        return res

    def get_admin_division_list(self, org_list, condition, page=None, count=None):
        '''# 查询行政区划列表'''
        keys = ['id', 'name', 'is_no_myself']
        values = self.get_value(condition, keys)
        # permission_keys = ['user_type']
        # permission_values = self.get_value(
        #     permission_condition, permission_keys)
        _filter = MongoBillFilter()
        _filter.lookup_bill('PT_Administration_Division', 'parent_id', 'id', 'adminDivision')\
            .add_fields({
                'parent_name': '$adminDivision.name',
                'create_date': self.ao.date_to_string('$create_date'),
                'modify_date': self.ao.date_to_string('$modify_date')})\
            .match_bill((C('id') != values['is_no_myself'])
                   & (C('id') == values['id'])
                   & (C('organization_id').inner(org_list))
                   & (C('name').like(values['name']))
                   )\
            .project({'_id': 0, 'adminDivision._id': 0})
        res = self.page_query(
            _filter, "PT_Administration_Division", page, count)
        return res

    def get_all_admin_division_list(self, condition, page=None, count=None):
        '''# app查询所有的行政区划列表'''
        keys = ['id']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == values['id'])).project({'_id': 0})
        res = self.page_query(
            _filter, "PT_Administration_Division", page, count)
        return res

    def get_admin_division_tree_list(self, org_list, condition, page=None, count=None, admin_area_id=None):
        '''# 查询行政区划列表 树形结构的数组'''
        # 获取当前组织机构的行政区划Id
        _filter = MongoBillFilter()
        if admin_area_id is None:
            _filter.match_bill((C('id').inner(org_list)))\
                .project({'_id': 0})
            res_user = self.query(
                _filter, "PT_User")
            if len(res_user) > 0:
                admin_area_id = res_user[0]['admin_area_id']
        keys = ['id', 'name', 'is_no_myself']
        values = self.get_value(condition, keys)
        # permission_keys = ['user_type']
        # permission_values = self.get_value(
        #     permission_condition, permission_keys)
        _filter = MongoBillFilter()
        if 'name' in condition.keys():
            _filter.match_bill((C('name') == values['name']))\
                .add_fields({
                    'title': '$name',
                    'value': '$id',
                    'key': '$id',
                    'children': []
                })\
                .project({'_id': 0})
        else:
            _filter.match_bill((C('id') == admin_area_id))\
                .add_fields({
                    'title': '$name',
                    'value': '$id',
                    'key': '$id',
                    'children': []
                })\
                .project({'_id': 0})
        res = self.page_query(
            _filter, "PT_Administration_Division", page, count)
        result = []
        if len(res['result']) > 0:
            for data in res['result']:
                new_res = self.query_child(data['id'])
                r_data = self.xuhuan(new_res, data)
                result.append(r_data)

        res['result'] = result
        return res

    def xuhuan(self, new_res, return_data):
        if len(new_res) > 0:
            return_data['children'] = new_res
            for data in new_res:
                child_data = self.query_child(data['id'])
                self.xuhuan(child_data, data)
        return return_data

    def query_child(self, admin_id):
        _filter = MongoBillFilter()
        _filter.match_bill((C('parent_id') == admin_id))\
            .add_fields({
                'title': '$name',
                'value': '$id',
                'key': '$id',
                'children': []
            })\
            .project({'_id': 0})
        res = self.query(
            _filter, "PT_Administration_Division")
        return res

    def update_admin_division(self, adminDivision):
        '''# 修改行政区划'''
        res = 'Fail'
        data_info = get_info({**adminDivision}, self.session)
        # 判断编号是否唯一
        if 'code' in data_info.keys():
            code = data_info['code']
            _filter = MongoBillFilter()
            _filter.match_bill((C('code') == code)).project({'_id': 0})
            business_area_data = self.query(
                _filter, "PT_Administration_Division")
            if len(business_area_data) > 0 and ('id' not in adminDivision or business_area_data[0]['id'] != adminDivision['id']):
                return code+'编号已存在！'
        if 'id' in adminDivision.keys():
            if adminDivision['id'] == adminDivision['parent_id']:
                return '不能选择当前行政区划'
            _filter = MongoBillFilter()
            _filter.match_bill(
                (C('parent_id') == adminDivision['id'])).project({'_id': 0})
            parent_data = self.query(_filter, "PT_Administration_Division")
            _filter_old = MongoBillFilter()
            _filter_old.match_bill(
                (C('id') == adminDivision['id'])).project({'_id': 0})
            old_data = self.query(_filter_old, "PT_Administration_Division")
            print('old_data>', old_data)
            if len(parent_data) > 0 and ('parent_id' not in old_data[0] or old_data[0]['parent_id'] != adminDivision['parent_id']):
                return '该区域已有下级关联，不能更改上级区域'
            flag = OperationType.update.value
        else:
            flag = OperationType.add.value
        bill_id = self.bill_manage_server.add_bill(
            flag, TypeId.businessArea.value, data_info, 'PT_Administration_Division')
        if bill_id:
            res = 'Success'
        return res

    def del_admin_division(self, ids):
        '''# 删除行政区划'''
        res = 'Fail'
        for admin_division_id in ids:
            _filter = MongoBillFilter()
            _filter.match_bill((C('admin_id') == admin_division_id)).project(
                {'_id': 0})
            business_area_data = self.query(_filter, "PT_Business_Area")
            _filter2 = MongoBillFilter()
            _filter2.match_bill((C('id') == admin_division_id)).project(
                {'_id': 0})
            data = self.query(_filter2, "PT_Administration_Division")
            if len(business_area_data) > 0:
                res = '该行政区划已被引用，无法删除'
            else:
                if len(data) > 0:
                    self.bill_manage_server.add_bill(OperationType.delete.value,
                                                     TypeId.businessArea.value, data[0], 'PT_Administration_Division')
                res = 'Success'
        return res
